﻿import { initShaders } from './gllib';
import { vertexSHADER, fragmentSHADER } from './shader_Vertex.js'
import Config from './mapConfig';
import $ from "jquery";
import provider from "../../stores/provider.js"
// import { useCanvasStore } from '../stores/default'
// const useCanvas = useCanvasStore()
const url = import.meta.env.VITE_backurl
const urlJxh = import.meta.env.VITE_backurl_jxh
const url_gg=import.meta.env.VITE_backurl_gg

L.Scalarlayer = L.Layer.extend({
  includes: L.Mixin.Events,

  texture_data: null,
  g_texUnit: false,
  g_texUnit1: false,
  g_texUnit2: false,

  options: {
    zindex: 0,
    opacity: 1,
    type: 'wave', //wind wave rwave
    showLabel: false,
    minval: 0.2,
    scalarColor: null, //色带配置
    labelCell: 64, //label显示密度   
    magnification: 1, //放大倍率   
  },

  minValue: 0, //数据极小值
  maxValue: 0, //数据极大值
  colorTotalNum: 200, //色带插值后总的个数
  colorBarCanvas: document.createElement('canvas'),

  initialize: function (options) {
    L.setOptions(this, options);
  },

  onAdd: function (map) {
    let self = this;
    self._map = map;
    if (!this._container) {
      this._initCanvas();
    }
    map._panes.overlayPane.appendChild(this._container);
    // map.on('moveend', this._reset, this);
    // map.on('zoomstart', this._clearCanvas, this);
    // map.on('zoomend', this.__draw, this);

    map.on('move', this._reset, this);
    map.on('zoom', this._reset, this);
    if (map.options.zoomAnimation && L.Browser.any3d) {
      map.on('zoomanim', this._animateZoom, this);
    }
    // self.initExtreme();
  },

  /**初始化色带纹理及数据极值 */
  initExtreme: function () {
    let self = this;
    let colorbarArr = [];
    let linshi11 = self.options.scalarColor.sort(function (a, b) { //按value进行排序
      return a.value - b.value;
    });
    self.minValue = linshi11[0].value;
    self.maxValue = linshi11[linshi11.length - 1].value;
    let unitColorNum = self.colorTotalNum / (self.maxValue - self.minValue);
    for (let iii = 0; iii < linshi11.length - 1; iii++) {
      let thisColors = Math.ceil(unitColorNum * (linshi11[iii + 1].value - linshi11[iii].value));
      let abc = self.interpolationColor(linshi11[iii].color, linshi11[iii + 1].color, thisColors);
      colorbarArr = colorbarArr.concat(abc);
    }
    let colorbar = document.createElement('canvas');
    colorbar.width = 1;
    colorbar.height = colorbarArr.length;
    let colorbarctx = colorbar.getContext('2d');
    let colorbardata = colorbarctx.getImageData(0, 0, 1, colorbar.height);
    for (let i = 0; i < colorbarArr.length; i++) {
      colorbardata.data[i * 4] = colorbarArr[i].r;
      colorbardata.data[i * 4 + 1] = colorbarArr[i].g;
      colorbardata.data[i * 4 + 2] = colorbarArr[i].b;
      colorbardata.data[i * 4 + 3] = 255;
    }
    self.colorbardata = colorbardata;

    //创建图例dom
    let canvas = document.createElement('div');
    // 打印当前浏览器url
    // console.log(window.location.href);
    if (window.location.href.includes('chunde')) {
      $(canvas).attr("id", "scalarLegend");
      $(canvas).css({
        "position": "absolute",
        "z-index": "999",
        "bottom": "15px",
        "left": "15px",
        "dispaly": "flex",
        "flex-direction": "column",
        "border": "1px solid #ccbb86",
        "box-shadow": "0 0 5px 0 #fff"
      });
    } else {
      $(canvas).attr("id", "scalarLegend");
      // $(canvas).css({
      //   "position": "fixed",
      //   "z-index": "9999",
      //   "top": "190px",
      //   "left": "10px",
      //   "dispaly": "flex",
      //   "flex-direction": "column",
      //   "border": "1px solid #ccbb86",
      //   "box-shadow": "0 0 5px 0 #fff"
      // });
      $(canvas).css({
        "position": "absolute",
        "z-index": "999",
        // "top": "250px",
        'bottom': '30px',
        // "left": "15px",
        "right": "80px",
        "dispaly": "flex",
        "flex-direction": "column",
        "border": "1px solid #ccbb86",
        "box-shadow": "0 0 5px 0 #fff"
      });
    }

    document.getElementById("map").appendChild(canvas)
    // document.body.appendChild(canvas)
  },

  onRemove: function (map) {
    let self = this;
    try {
      if (self.webglcontext) {
        self.webglcontext.clearColor(0.0, 0.0, 0.0, 0.0);
        self.webglcontext.clear(self.webglcontext.COLOR_BUFFER_BIT);
        self.labelcontext.clearRect(0, 0, 5000, 5000);
      }
    } catch (e) {
      console.log(e);
    }
    self._clearCanvas()
    self.texture_data = null
    map.getPanes().overlayPane.removeChild(this._container);
    // map.off('moveend', this._reset, this);
    // map.off('zoomstart', this._clearCanvas, this);
    // map.off('zoomend', this.__draw, this);
    map.off('move', this._reset, this);
    map.off('zoom', this._reset, this);
    if (map.options.zoomAnimation) {
      map.off('zoomanim', this._animateZoom, this);
    }
    Config.curData = {}
    Config.ImgData = {}
    //移除图例canvas
    if (!Config.isShow.onSS) document.getElementById("map").removeChild(document.getElementById("scalarLegend"))
  },

  // 只是重写了一遍而已
  addTo: function (map) {
    map.addLayer(this);
    return this;
  },

  bringToBack: function () {//将图层置于底层，没用到过就是没用
    let pane = this._map._panes.overlayPane;
    if (this._canvas) {
      pane.insertBefore(this._canvas, pane.firstChild);
    }
    return this;
  },

  _initCanvas: function () {
    this._container = L.DomUtil.create('div', 'leaflet-image-layer');
    this._canvas = L.DomUtil.create('canvas', '');
    this._canvas_label = L.DomUtil.create('canvas', '');
    this._setZindex(this.options.zindex);
    if (this._map.options.zoomAnimation && L.Browser.any3d) {
      L.DomUtil.addClass(this._canvas, 'leaflet-zoom-animated');
      L.DomUtil.addClass(this._canvas_label, 'leaflet-zoom-animated');
    } else {
      L.DomUtil.addClass(this._canvas, 'leaflet-zoom-hide');
      L.DomUtil.addClass(this._canvas_label, 'leaflet-zoom-animated');
    }
    this._container.appendChild(this._canvas);
    this._container.appendChild(this._canvas_label);
    L.extend(this._canvas, {
      onselectstart: L.Util.falseFn,
      onmousemove: L.Util.falseFn,
      onload: L.bind(this._onCanvasLoad, this)
    });
    L.extend(this._canvas_label, {
      onselectstart: L.Util.falseFn,
      onmousemove: L.Util.falseFn,
      onload: L.bind(this._onCanvasLoad, this)
    });
  },

  _setTransform: function (el, offset, scale) {
    let pos = offset || new L.Point(0, 0);
    el.style[L.DomUtil.TRANSFORM] = (L.Browser.ie3d ? 'translate(' + pos.x + 'px,' + pos.y + 'px)' : 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') + (scale ? ' scale(' + scale + ')' : '');
  },

  _animateZoom: function (e) {
    let map = this._map,
      container = this._container,
      canvas = this._canvas,
      scale = map.getZoomScale(e.zoom),
      nw = map.containerPointToLatLng([0, 0]),
      se = map.containerPointToLatLng([canvas.width, canvas.height]),
      topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
      size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
      origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
  },

  _onCanvasLoad: function () {
    this.fire('load');//触发load事件
  },

  _clearCanvas: function () {
    let self = this;
    try {
      let canvas_label = self._canvas_label;
      let ctx_label = canvas_label.getContext('2d');
      ctx_label.clearRect(0, 0, canvas_label.clientWidth, canvas_label.clientHeight);
      let canvas = this._canvas;
      let gl = canvas.getContext('experimental-webgl', {
        preserveDrawingBuffer: true
      });
      gl.clearColor(0.0, 0.0, 0.0, 0.0);
      gl.clear(gl.COLOR_BUFFER_BIT);
      gl.clear(gl.DEPTH_BUFFER_BIT);
    } catch (e) {
      console.log(e);
    }
  },

  _reset: function () {
    let self = this;
    if (!this._map) {
      return;
    }
    let container = this._container,
      canvas = this._canvas,
      canvas_label = this._canvas_label;
    let size = this._map.getSize(),
      lt = this._map.containerPointToLayerPoint([0, 0]);
    L.DomUtil.setPosition(container, lt);
    container.style.width = size.x + 'px';
    container.style.height = size.y + 'px';

    //绘制底色的canvas    
    canvas.width = size.x * self.options.magnification;
    canvas.height = size.y * self.options.magnification;
    canvas.style.width = size.x + "px";
    canvas.style.height = size.y + "px";
    canvas.style.position = 'absolute';
    canvas.style.left = '0';
    canvas.style.top = '0';

    // 创建label图层的canvas
    canvas_label.width = size.x;
    canvas_label.height = size.y;
    canvas_label.style.width = size.x + "px";
    canvas_label.style.height = size.y + "px";
    canvas_label.style.position = 'absolute';
    canvas_label.style.left = '0';
    canvas_label.style.top = '0';

    this.width = size.x;
    this.height = size.y;

    self.__draw(this.header, this.data);
  },

  _setZindex: function (Zindex) {
    this._container.style.zIndex = Zindex;
  },

  setOpacity: function (val) {
    this.options.opacity = val;
    this._reset();
  },

  setScalarColor: function (val) {
    let self = this;
    self.options.scalarColor = val;
    self.initExtreme();
    self._reset();
  },

  _setdata: function (isGlobal) {
    let self = this, map = this._map;
    self.texture_data = null;
    // this._clearCanvas()
    self._reset();
  },

  __draw: function () {
    let self = this, map = this._map;
    let referDrawTime = Config.time.dataTimeUTC,
      referDrawTime2 = Config.time.dataTime,
      dataPath = Config.urls.dataPath, rdataPath = Config.urls.rdataPath;

    if (self.options.type == 'wave') {
      // http://www.oceanread.com/output/2023111500/wave_G_full.png
      self.texturepath=`${url_gg}/output/${Config.queryTime}/wave_G_full.png`;
      // // console.log(Config.queryTime);
      // // Config.queryTime的前8位
      // let wjj = Config.queryTime.substring(0, 8);
      // let imgName = Config.queryTime.substring(8, 10);
      // // self.texturepath = `${dataPath}/${referDrawTime}/wave_G_full.png`;
      // // self.texturepath=`${dataPath}/${referDrawTime}/wave_G_full.png`

      // // self.texturepath = 'http://116.204.97.29:9001/img/wave_G_full.png'
      // // self.texturepath =Math.random() > 0.5 ? url+'/img/wz_hl_1.png':url+'/img/wz_hl_2.png'
      // // self.texturepath=url+`/img/output/${Config.queryTime}/taizh_wz_tp_wave.png`
      // if (provider.key == 'sa') {
      //   self.texturepath = url + `/imgSa/wave/${wjj}/ww3.${imgName}.png`
      // } else {
      //   self.texturepath = url + `/img/wave/${wjj}/ww3.${imgName}.png`
      // }
      // self.texturepath = url + '/img/wave_G_full.png'
    } else if (self.options.type == 'wind') {
      self.texturepath = `${url_gg}/output/${Config.queryTime}/wind_G_full.png`;
      // http://www.oceanread.com/output/2023111500/wind_G_full.png
      // let wjj = Config.queryTime.substring(0, 8);
      // let imgName = Config.queryTime.substring(8, 10);
      // if (provider.key == 'sa') {
      //   self.texturepath = url + `/imgSa/wind/${wjj}/wind.${imgName}.png`
      // } else {
      //   self.texturepath = url + `/imgAis/wind/${wjj}/wind.${imgName}.png`
      // }
      // http://www.oceanread.com/output/2023111500/wind_G_full.png
      // self.texturepath = `http://www.oceanread.com/output/2023111500/wind_G_full.png`;
    } else if (self.options.type == 'rwave') {
      self.texturepath = `${rdataPath}/${referDrawTime2}/wz_wave.png`;
    } else if (self.options.type == 'rtpwave') {
      let curRtpwave = Config.isShow.curRtpwave
      curRtpwave = curRtpwave?.[1] ? (curRtpwave[1] + "_") : ""
      self.texturepath = `${rdataPath}/${referDrawTime2}/${curRtpwave}wz_tp_wave.png`;
    } else if (self.options.type == 'tide') {
      // self.texturepath = `${rdataPath}/${referDrawTime2}/wz_tide.png`;
      let wjj = Config.queryTime.substring(0, 8);
      let imgName = Config.queryTime.substring(8, 10);
      if (provider.key == 'sa') {
        self.texturepath = url + `/imgSa/tide/${wjj}/tide.${imgName}.png`
      } else {
        self.texturepath = url + `/img/tide/${wjj}/tide.${imgName}.png`
      }
    } else if (self.options.type == 'surge') {
      // let curSurge = Config.isShow.curSurge
      // // self.texturepath = `${rdataPath}/${referDrawTime2}/wz_surge${curSurge?.[0] ?? ""}_fbc${curSurge[1]}_${self.options?.surgeTP ?? ""}.png`;
      // // self.texturepath = 'http://www.wzhy.com.cn:8000/jxhDatas/2018070701/wz_surge_cacl_fbc1808a2_cent.png'
      // // self.texturepath = './public/img/wz_surge_cacl_fbc1808a2_cent.png'
      // // self.texturepath = 'http://116.204.97.29:9001/img/wz_wave.png'
      // // self.texturepath = 'http://116.204.97.29:9001/img/wz_surge_cacl_fbc1808a2_cent.png'
      // // wz_surge_cacl_fbc2106_cent.png
      // // self.texturepath = Math.random() > 0.5 ? 'http://116.204.97.29:9001/img/wz_surge_cacl_fbc1808a2_cent.png' : 'http://116.204.97.29:9001/img/wz_surge_cacl_fbc2106_cent.png'
      // // self.texturepath = url + '/img/wz_surge_cacl_fbc1808a2_cent.png'
      // let wjj = Config.queryTime.substring(0, 8);
      // let imgName = Config.queryTime.substring(8, 10);

      self.texturepath = urlJxh + `/jxhDatas/${Config.queryTime}/${Config.surgeName}.png`
    }

    Config.curData[self.options.type] = [];

    let canvas_label = self._canvas_label;
    self.labelcontext = canvas_label.getContext('2d');
    if (L.Browser.canvas && map) {
      if (!Config.ImgData[self.texturepath]) {
        (function (rtim, url) {
          let image = new Image();
          image.crossOrigin = 'anonymous';
          image.src = url;
          // Config.showLoading();
          image.onload = function () {
            Config.hideLoading();
            let referDrawTime2 = Config.time.dataTimeUTC;
            if (rtim === referDrawTime2) {
              self.drawByImage(image, url);
            }
          };
          image.onerror = function () {
            Config.hideLoading();
            switch (self.options.type) {
              case 'wave':
                // alertInfo('当前时刻无全球海浪数据', 2500, "wave");
                break;
              case 'wind':
                // alertInfo('当前时刻无全球海风数据', 2500, "wind");
                break;
              case 'rwave':
                if (!Config.isShow.onSS && map._zoom > Config.mapObj.jxhzoomF) {
                  Config.mapObj.jxhzoom = 14
                  map.fire("zoomend")
                }
                // alertInfo('当前时刻无精细化海浪数据，已切换为全球浪数据', 10000, "no_rwave");
                break;
              case 'rtpwave':
                // alertInfo('当前时刻无台风浪数据', 2500, "rtpwave");
                break;
              case 'tide':
                // alertInfo('当前时刻无潮位数据', 2500, "tide");
                break;
              case 'surge':
                // alertInfo('当前时刻无该风暴増水数据', 2500, "surge");
                break;
              default:
              // alertInfo('当前时刻无数据', 2500, "oth");
            }
            try {
              let gl = self.webglcontext;
              if (gl) {
                gl.clearColor(0.0, 0.0, 0.0, 0.0);
                gl.clear(gl.COLOR_BUFFER_BIT);
                gl.clear(gl.DEPTH_BUFFER_BIT);
              }
            } catch (e) {
              console.log(e);
            }
          };
        })(referDrawTime, self.texturepath);
      } else {
        (function (rtim, url) {
          let referDrawTime2 = Config.time.dataTimeUTC;
          if (rtim === referDrawTime2) {
            let image = Config.ImgData[self.texturepath].image;
            let data = Config.ImgData[self.texturepath].data;
            self.drawMethod(image, data);
          }
        })(referDrawTime, self.texturepath);
      }
    }
  },

  /**
   * 用图片数据绘制
   * @param {any} image imagedata
   */
  drawByImage: function (image, url) {
    let self = this, can = document.createElement('canvas');
    can.width = image.width, can.height = image.height;

    let ImgdataCtx = can.getContext('2d');
    ImgdataCtx.drawImage(image, 0, 0);

    // getImageData的作用是返回ImageData对象，该对象拷贝了画布指定矩形的像素数据
    let data = [], image0 = ImgdataCtx.getImageData(0, 0, image.width, image.height), imgdat0 = image0.data,
      angleInter = ["rwave"].includes(self.options.type) ? 0 : 180;
    if (self.options.type == "rtpwave") angleInter = 0

    // console.log(data);

    //这个双for对显示图像没有作用
    for (let i = 0; i < image0.height; i++) {
      data[i] = [];
      for (let j = 0; j < image0.width; j++) {
        let x = (i * 4) * image0.width + (j * 4)
        let r = imgdat0[x], g = imgdat0[x + 1], b = imgdat0[x + 2], a = imgdat0[x + 3];
        if (a == 0) {
          data[i][j] = -999
          continue
        }
        let value_0 = 0;
        data[i][j] = value_0.toFixed(1);
        if (self.options.type == 'wind') {
          let u = b >= 10 ? r / 10 : -(r / 10), v = b % 10 == 1 ? g / 10 : -(g / 10);
          let uvObj = self.computeWindUV(u, v);
          value_0 = {
            value: uvObj.value,
            angle: uvObj.angle
          };
          data[i][j] = value_0;
        } else if (["wave", "rwave", 'rtpwave'].includes(self.options.type)) {
          let value_w = r + g / 100, angle_origin_w = b / 255 * 360, angle = (angle_origin_w + angleInter) % 360
          value_0 = {
            value: parseFloat(value_w.toFixed(1)),
            angle: +((+angle).toFixed(1))
          }
          data[i][j] = value_0
        } else if (["tide", "surge"].includes(self.options.type)) {
          let value_w = (r + g / 100 + b / 10000) * 100
          value_w = a > 254 ? value_w : -value_w
          value_0 = {
            value: parseFloat(value_w.toFixed(2)),
            angle: 0.0
          }
          data[i][j] = value_0
        }
      }
    }
    // let rowRange = [], colRange = []
    // if (self.options.type == 'wind') {
    //   rowRange = [78, 81]
    //   colRange = [49, 55]
    // } else {
    //   rowRange = [509, 546]
    //   colRange = [301, 407]
    // }
    // let max = 0, min = Math.pow(10, 10)
    // for (let i = rowRange[0]; i < rowRange[1]; i++) {
    //   for (let j = colRange[0]; j < colRange[1]; j++) {
    //     if (data[i][j].value > max) max = data[i][j].value
    //     if (data[i][j].value < min) min = data[i][j].value
    //   }
    // }

    // if ([].includes(self.options.type)) {
    //   let min = Config.ColorRange[self.options.type][0], max = Config.ColorRange[self.options.type][1]
    //   let scalarColor = Config.scalarColor[self.options.type]
    //   // 对max进行取整
    //   max = Math.ceil(max)
    //   min = Math.floor(min)


    //   let colorLength = scalarColor.length
    //   let step = (max - min) / (colorLength - 1)

    //   if (step < 0.2) {
    //     step = 0.2
    //   } else if (step < 0.5) {
    //     step = 0.5
    //   }
    //   else {
    //     step = Math.ceil(step)
    //   }
    //   for (let i = 0; i < colorLength; i++) {
    //     scalarColor[i].value = (Math.round((min + step * i) * 10) / 10).toString()
    //   }
    // }

    Config.ImgData[url] = { image: image0, data }

    self.initExtreme();
    // console.log(Config.AllLayers.tideLayer.options.scalarColor[0]);
    self.drawMethod(image, data);
  },

  initColor: function (image, url) {

  },

  /**
   * 读取图片后绘制方法
   * @param {any} image 图片对象
   * @param {any} imgdat 图片数据对象
   */
  drawMethod: function (image, data) {

    let self = this, canvas = this._canvas;
    let Cwidth = canvas.clientWidth;
    let Cheight = canvas.clientHeight;
    // Config.rasterHeader.rtpwave.startLon=123
    let rasterHeader = Config.rasterHeader
    // let  range = {
    //     wind: rasterHeader.global1,
    //     wave: rasterHeader.wave,
    //     rwave: rasterHeader.rwave,
    //     rtpwave: rasterHeader.rtpwave,
    //     tide: rasterHeader.rwave,
    //     surge: rasterHeader.rtpwave,
    //   }[self.options.type];
    let range = {}
    if (provider.key == 'sa') {
      range = {
        wind: rasterHeader.global1,
        wave: rasterHeader.waveSa,
        rwave: rasterHeader.rwave,
        rtpwave: rasterHeader.rtpwave,
        tide: rasterHeader.tideSa,
        surge: rasterHeader.rtpwave,
      }[self.options.type];
    } else {
      range = {
        wind: rasterHeader.global1,
        wave: rasterHeader.wave,
        rwave: rasterHeader.rwave,
        rtpwave: rasterHeader.rtpwave,
        tide: rasterHeader.rwave,
        surge: rasterHeader.rtpwave,
      }[self.options.type];
    }

    let startLon = range.startLon, startLat = range.startLat,
      endLon = range.endLon, endLat = range.endLat,
      uscale = range.uscale, vscale = range.vscale;

    let header = {
      uscale: uscale,
      vscale: vscale,
      startLat: startLat,
      startLon: startLon,
      endLon: endLon,
      endLat: endLat,
      nx: image.width,
      ny: image.height,
      nodata: -999
    };

    // if (["rwave", "rtpwave", "tide", "surge"].includes(self.options.type)) {
    //   uscale = (endLon - startLon) / range?.pixel || 1, vscale = (startLat - endLat) / range?.pixel
    //   Object.assign(header, {
    //     "uscale": uscale,
    //     "vscale": vscale
    //   });
    // }

    self.data = data;
    self._header = header;
    self.texture_data = image;
    self._drawbytexture();
    Config.curData[self.options.type] = self.data;
    self._drawColorBar(self.options.type);

    self._drawlabel(self.labelcontext, Cwidth, Cheight, header.startLon, header.startLat, header.nodata, data, header.uscale, header.vscale);
  },

  // 皆系于此
  _drawbytexture: function () { //使用纹理绘图
    let self = this;
    let canvas = this._canvas;

    let gl = canvas.getContext('experimental-webgl', {
      preserveDrawingBuffer: true
    });

    gl.viewport(0, 0, canvas.width, canvas.height);
    self.webglcontext = gl;
    gl.clearColor(0.0, 0.0, 0.0, 0.0);
    gl.clear(gl.COLOR_BUFFER_BIT);//清空颜色缓冲区
    gl.clear(gl.DEPTH_BUFFER_BIT);//清空深度缓冲区

    if (!gl) {
      console.log("Failed to get the rendering context for WebGL");
      return;
    }

    if (["wind", "wave", "rwave", "rtpwave", "tide", "surge"].includes(self.options.type)) {
      if (!initShaders(gl, vertexSHADER, fragmentSHADER)) {
        console.log("初始化着色器失败！");
        return;
      }
    } else {
      console.log("无效图层类型！");
      return;
    }

    let n = self.initVertexBuffers(gl); //设置顶点的相关信息
    if (n < 0) {
      console.log("无法获取到点的数据");
      return;
    }
    if (!self.initTextures(gl, n)) { //配置纹理
      console.log('无法配置纹理');
      return;
    }
  },

  initVertexBuffers: function (gl) { //设置顶点
    let self = this, texturey = 1.0;
    if (!this._map) return;
    let verticesSizes = new Float32Array([ //四个顶点的位置和纹理数据范围
      -1, 1, 0.0, texturey,
      -1, -1, 0.0, 0.0,
      1, 1, 1.0, texturey,
      1, -1, 1.0, 0.0
    ]);

    let n = 4;
    let vertexSizeBuffer = gl.createBuffer();
    if (!vertexSizeBuffer) {
      console.log('无法创建缓冲区');
      return -1;
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexSizeBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, verticesSizes, gl.STATIC_DRAW);
    let a_Position = gl.getAttribLocation(gl.program, 'a_Position'); //
    if (a_Position < 0) {
      console.log('无法获取到存储位置');
      return;
    }

    //获取数组一个值所占的字节数
    let fsize = verticesSizes.BYTES_PER_ELEMENT;
    //将顶点坐标的位置赋
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, fsize * 4, 0);
    gl.enableVertexAttribArray(a_Position);

    var dataRange = gl.getUniformLocation(gl.program, 'dataRange');
    if (!dataRange) {
      console.log('未能获取dataRange');
      return;
    }
    gl.uniform4f(dataRange, self._header.startLat, self._header.endLat, self._header.startLon, self._header.endLon);

    var dataType = gl.getUniformLocation(gl.program, 'dataType');
    if (!dataType) {
      console.log('未能获取dataType');
      return;
    }
    if (self.options.type == "wind") {
      gl.uniform1f(dataType, 1.0);
    } else if (['wave', 'rwave', "rtpwave"].includes(self.options.type)) {
      gl.uniform1f(dataType, 2.0);
    } else if (['tide', 'surge'].includes(self.options.type)) {
      gl.uniform1f(dataType, 3.0);
    }

    let u_Scale = gl.getUniformLocation(gl.program, 'u_Scale');
    if (!u_Scale) {
      console.log('未能获取u_Scale的存储位置！');
      return;
    }
    gl.uniform1f(u_Scale, self._header.uscale);

    let v_Scale = gl.getUniformLocation(gl.program, 'v_Scale');
    if (!v_Scale) {
      console.log('未能获取v_Scale的存储位置！');
      return;
    }
    gl.uniform1f(v_Scale, self._header.vscale);

    let u_Startlon = gl.getUniformLocation(gl.program, 'u_Startlon');
    if (!u_Startlon) {
      console.log('未能获取u_Startlon的存储位置！');
      return;
    }
    gl.uniform1f(u_Startlon, self._header.startLon);

    let u_Startlat = gl.getUniformLocation(gl.program, 'u_Startlat');
    if (!u_Startlat) {
      console.log('未能获取u_Startlat的存储位置！');
      return;
    }
    gl.uniform1f(u_Startlat, self._header.startLat);

    let pic_width = gl.getUniformLocation(gl.program, 'pic_width');
    if (!pic_width) {
      console.log('未能获取pic_width的存储位置！');
      return;
    }
    gl.uniform1f(pic_width, self.texture_data.width);

    let pic_height = gl.getUniformLocation(gl.program, 'pic_height');
    if (!pic_height) {
      console.log('未能获取pic_height的存储位置！');
      return;
    }
    gl.uniform1f(pic_height, self.texture_data.height);

    let leftlon = gl.getUniformLocation(gl.program, 'leftlon');
    if (!leftlon) {
      console.log('未能获取leftlon的存储位置！');
      return;
    }
    let Llon = self._map.containerPointToLatLng(L.point(0, 0)).lng;
    gl.uniform1f(leftlon, Llon);

    let Rlon = self._map?.containerPointToLatLng(L.point(self._canvas.clientWidth, 0))?.lng;
    let cell = (Rlon - Llon) / (self._canvas.clientWidth);

    let lonspan = gl.getUniformLocation(gl.program, 'lonspan');
    if (!lonspan) {
      console.log('未能获取lonspan的存储位置！');
      return;
    }
    gl.uniform1f(lonspan, Rlon - Llon);

    let widhei = gl.getUniformLocation(gl.program, 'widhei');
    if (!widhei) {
      console.log('未能获取widhei的存储位置！');
      return;
    }
    gl.uniform2f(widhei, self._canvas.width, self._canvas.height);

    let alpa = gl.getUniformLocation(gl.program, '_Alpha');
    if (!alpa) {
      console.log('未能获取_Alpha的存储位置！');
      return;
    }
    gl.uniform1f(alpa, self.options.opacity);

    let minValue = gl.getUniformLocation(gl.program, 'minValue');
    if (!minValue) {
      console.log('未能获取minValue的存储位置！');
      return;
    }
    gl.uniform1f(minValue, self.minValue);

    let maxValue = gl.getUniformLocation(gl.program, 'maxValue');
    if (!maxValue) {
      console.log('未能获取maxValue的存储位置！');
      return;
    }
    gl.uniform1f(maxValue, self.maxValue);
    return n;
  },

  initTextures: function (gl, n) { //设置纹理
    let self = this;
    gl.getExtension('OES_texture_float');
    gl.getExtension('OES_texture_float_linear');
    let texture = gl.createTexture(); //创建纹理对象
    let texture1 = gl.createTexture();
    let texture2 = gl.createTexture();
    if (!texture || !texture1 || !texture2) {
      console.log('无法创建纹理对象');
      return;
    }
    //获取u_Sampler的存储位置
    let u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
    let u_Sampler1 = gl.getUniformLocation(gl.program, 'u_Sampler1');
    let u_Sampler2 = gl.getUniformLocation(gl.program, 'u_Sampler2');
    if (u_Sampler < 0 || u_Sampler1 < 0 || u_Sampler2 < 0) {
      console.log('无法获取变量的存储位置');
      return;
    }

    //以下是纬度纹理
    let Cwidth = self._canvas.clientWidth;
    let Cheight = self._canvas.clientHeight;
    let canvas_lat = document.createElement('canvas');
    canvas_lat.width = 1;
    canvas_lat.height = Cheight;
    if (Cheight == 0) return;
    let latctx = canvas_lat.getContext('2d');
    let latlngTexture = latctx.getImageData(0, 0, 1, Cheight);
    for (let i = 0; i < Cheight; i++) {
      let lat = self._map.containerPointToLatLng(L.point(0, i)).lat;
      if (lat < 0) {
        latlngTexture.data[i * 4 + 3] = 255; //a
      } else {
        latlngTexture.data[i * 4 + 3] = 0; //a
      }
      lat = Math.abs(lat);
      let latInt = parseInt(lat);
      latlngTexture.data[i * 4] = latInt; //r
      let xiaoshu = (lat - latInt !== 0) ? ((lat - latInt).toString().split('.')[1]) : ('0');
      if (xiaoshu.length < 12) {
        xiaoshu = xiaoshu.PadRight(12, '0');
      }
      latlngTexture.data[i * 4 + 1] = parseInt(xiaoshu.substring(0, 2)); //g
      latlngTexture.data[i * 4 + 2] = parseInt(xiaoshu.substring(2, 4)); //b
    }
    self.loadTexture(gl, n, texture, u_Sampler, self.texture_data, 0); //数据纹理
    self.loadTexture(gl, n, texture1, u_Sampler1, latlngTexture, 1); //经纬度纹理
    self.loadTexture(gl, n, texture2, u_Sampler2, self.colorbardata, 2); //色带纹理
    return true;
  },

  loadTexture: function (gl, n, texture, u_Sampler, image, texUnit) { //载入纹理
    let self = this;
    //对纹理图像进行y轴反转
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
    //开启0号纹理单元
    if (texUnit == 0) {
      gl.activeTexture(gl.TEXTURE0);
      self.g_texUnit = true;
      //向target绑定纹理对象
      gl.bindTexture(gl.TEXTURE_2D, texture);
      //配置纹理参数
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      //配置纹理图像
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
      //将0号纹理传递给着色器
      gl.uniform1i(u_Sampler, texUnit);
    } else if (texUnit == 1) {
      gl.activeTexture(gl.TEXTURE1);
      self.g_texUnit1 = true;
      //向target绑定纹理对象
      gl.bindTexture(gl.TEXTURE_2D, texture);
      //配置纹理参数
      gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      //gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
      //配置纹理图像
      // gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, image.length / 4, 0, gl.RGBA, gl.FLOAT, image);
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
      //将0号纹理传递给着色器
      gl.uniform1i(u_Sampler, texUnit);
    } else if (texUnit == 2) {
      gl.activeTexture(gl.TEXTURE2);
      self.g_texUnit2 = true;
      //向target绑定纹理对象
      gl.bindTexture(gl.TEXTURE_2D, texture);
      //配置纹理参数
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); //NEAREST
      //配置纹理图像
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
      //将0号纹理传递给着色器
      gl.uniform1i(u_Sampler, texUnit);
    }
    //绘制
    if (self.g_texUnit && self.g_texUnit1 && self.g_texUnit2) {
      gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
      self.g_texUnit = false;
      self.g_texUnit1 = false;
      self.g_texUnit2 = false;
    }
  },

  setShowLabel: function (bool) {
    this.options.showLabel = bool;
    if (this._map) {
      this._reset();
    }
  },

  _drawlabel: function (ctx, Cwidth, Cheight, startLon, startLat, nodata, data, datacellu, datacellv) {
    let self = this, map = this._map;
    ctx.clearRect(0, 0, Cwidth, Cheight);
    if (!self.options.showLabel || !map) return;

    let currentzoom = map.getZoom(), currentbounds = map.getBounds();
    let leftup = currentbounds.getNorthWest(), rightdown = currentbounds.getSouthEast();
    let range = self._getRange(leftup, rightdown, currentzoom);
    let zr = Math.pow(2, currentzoom);
    for (let i = range.up; i <= range.down; i++) {
      for (let j = range.left; j <= range.right; j++) {
        let zheng = Math.floor(j / zr);
        let yu = j % zr;
        if (yu < 0) yu = yu + zr

        let row = i, col = yu
        let cellInterval = 2 * Math.PI / (256 * Math.pow(2, currentzoom))
        let firstX = col * cellInterval * 256 - Math.PI + cellInterval / 2
        let firstY = Math.PI - (row * cellInterval * 256) - cellInterval / 2
        let interval = this.options.labelCell
        for (let h = 0; h < 256 / interval; h++) {
          for (let w = 0; w < 256 / interval; w++) {
            try {
              let lonlat = self.getLonlat(firstX, firstY, cellInterval, w * interval, h * interval, interval / 2);
              let lon0 = lonlat.lon;
              let lat0 = lonlat.lat;
              let querylng = lon0;
              querylng = querylng % 360;
              if (querylng < 0) {
                querylng = querylng + 360;
              }
              let _row = Math.floor((startLat - lat0) / datacellv);
              let _col = Math.floor((querylng - startLon) / datacellu);
              if (_row < 0 || _row > data.length || _col < 0 || _col >= data[0].length) {
                continue;
              }
              let txt;
              if (data[_row][_col] == nodata) {
                continue;
              }
              if (['wind', 'wave', 'rwave', 'rtpwave', "tide", "surge"].includes(self.options.type)) {
                txt = +((+data[_row][_col].value).toFixed(1));
                if (['wave', 'rwave', 'rtpwave'].includes(self.options.type) && +txt <= 0.0) continue
              } else {
                txt = (+data[_row][_col]).toFixed(1);
              }
              ctx.font = '15px 微软雅黑';
              ctx.fillStyle = 'rgba(0,0,0,0.4)';
              ctx.textAlign = 'center';
              ctx.textBaseline = 'middle';

              // ctx.shadowColor = '#fff'; // 阴影颜色
              // ctx.shadowBlur = 20; // 阴影模糊级别
              // ctx.shadowOffsetX = 0; // 阴影在水平方向上的偏移量
              // ctx.shadowOffsetY = 0; // 阴影在垂直方向上的偏移量
              lon0 = lonlat.lon + 360 * zheng;
              let screenpoint = map.latLngToContainerPoint(L.latLng(lat0, lon0));
              ctx.fillText(txt, screenpoint.x, screenpoint.y);
            } catch (error) {
              continue;
            }
          }
        }
      }
    }
  },

  _getRange: function (leftup, rightdown, zoom) { //根据经纬度计算行列号
    var leftuprowcol = this._getCornerNum(leftup.lat, leftup.lng, zoom);
    var rightdownrowcol = this._getCornerNum(rightdown.lat, rightdown.lng, zoom);
    return {
      left: leftuprowcol.colNum === 0 ? leftuprowcol.colNum : leftuprowcol.colNum - 1,
      up: leftuprowcol.rowNum === 0 ? leftuprowcol.rowNum : leftuprowcol.rowNum - 1,
      right: rightdownrowcol.colNum,
      down: rightdownrowcol.rowNum
    };
  },

  _getCornerNum: function (lat, lon, level) { //计算横轴墨卡托投影下的坐标
    var d = Math.PI / 180;
    var x = lon * d;
    var y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
    y = y * Math.PI / 180;
    let rowNumber = (Math.PI - y) / (2 * Math.PI) * Math.pow(2, level); //先转墨卡托，用墨卡托求行列号
    let colNumber = (x + Math.PI) / (2 * Math.PI) * Math.pow(2, level);
    return {
      rowNum: Math.round(rowNumber),
      colNum: Math.round(colNumber)
    };
  },

  getLonlat: function (x, y, cell, xAdd, yAdd, jian) { //计算切片上点的坐标
    var lon = (x + xAdd * cell + jian * cell) / Math.PI * 180;
    var lat = 180 / Math.PI * (2 * Math.atan(Math.exp(((y - yAdd * cell - jian * cell) / Math.PI * 180) * Math.PI / 180)) -
      Math.PI / 2);
    return {
      lon: lon,
      lat: lat
    }
  },

  /**插值颜色 */
  interpolationColor: function (color1, color2, chazhigeshu) {
    var self = this;
    self.colorBarCanvas.width = chazhigeshu;
    self.colorBarCanvas.height = 1;
    var ctx = self.colorBarCanvas.getContext('2d');

    var grd = ctx.createLinearGradient(0, 1, chazhigeshu, 1);
    // grd.addColorStop(0, `rgb(${color1.r},${color1.g},${color1.b}`);
    // grd.addColorStop(1, `rgb(${color2.r},${color2.g},${color2.b}`);
    grd.addColorStop(0, color1);
    grd.addColorStop(1, color2);
    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, chazhigeshu, 1);
    let colorZong = [];
    for (let iii = 0; iii < chazhigeshu; iii++) {
      var colorData = ctx.getImageData(iii, 0, 1, 1).data;
      colorZong.push({
        r: colorData[0],
        g: colorData[1],
        b: colorData[2]
      });
    }
    return colorZong;
  },

  /**转换风场UV值 */
  computeWindUV: function (u_value, v_value) {
    let value = Math.sqrt(u_value * u_value + v_value * v_value);
    let angle = Math.acos(u_value / value);
    if (v_value < 0) {
      angle = -angle;
    }
    angle = Math.round(angle / Math.PI * 180.0 + 90);
    if (angle < 0) {
      angle = angle + 360;
    }
    angle = Math.round(360 - angle);
    value = value.toFixed(1);
    return {
      value: parseFloat(value),
      angle: angle
    };
  },

  _drawColorBar: function (type) {
    var dataObj = {
      wind: {
        color: [
          "rgb(82, 71, 141)",
          "rgb(57, 136, 199)",
          "rgb(82,185,94)",
          "rgb(200,207,63)",
          "rgb(255, 164, 62)",
          "rgb(204,90,99)",
          "rgb(143,33,76)",
          "rgb(43,0,1)",
        ],
        textcolor: [
          "rgb(255,255,255)",
          "rgb(255,255,255)",
          "rgb(0, 0, 0)",
          "rgb(0, 0, 0)",
          "rgb(0, 0, 0)",
          "rgb(0, 0, 0)",
          "rgb(0, 0, 0)",
          "rgb(255,255,255)",
        ],
        colorMark: [0, 6, 12, 18, 24, 30, 36, 42],
        titleText: 'm/s',
      },
      wave: {
        color: [
          'rgb(0, 31, 255)', 'rgb(71, 94, 255)', 'rgb(54, 152, 237)',
          'rgb(253, 255, 0)', 'rgb(208, 88, 44)', 'rgb(250, 11, 10)', 'rgb(187, 13, 19)'
        ],
        textcolor: [
          "rgb(255,255,255)", "rgb(0,0,0)", "rgb(0,0,0)",
          "rgb(0,0,0)", "rgb(0,0,0)", "rgb(0,0,0)", "rgb(255,255,255)",
        ],
        colorMark: [
          // 0, 2, 3, 4,
          // 6, 9, 14
          0, 2, 4, 6,
          8, 12, 14
        ],
        titleText: 'm',

        // { "color": "rgb(0, 31, 255)", "value": 0 },
        // { "color": "rgb(71, 94, 255)", "value": 2 },
        // { "color": "rgb(54, 152, 237)", "value": 4 },
        // { "color": "rgb(253, 255, 0)", "value": 6 },
        // { "color": "rgb(208, 88, 44)", "value": 8 },
        // { "color": "rgb(250, 11, 10)", "value": 12 },
        // { "color": "rgb(187, 13, 19)", "value": 14 } 
      },
      rtpwave: {
        color: [
          'rgb(0, 31, 255)', 'rgb(71, 94, 255)', 'rgb(54, 152, 237)',
          'rgb(253, 255, 0)', 'rgb(208, 88, 44)', 'rgb(250, 11, 10)', 'rgb(187, 13, 19)'
        ],
        textcolor: [
          "rgb(255,255,255)", "rgb(0,0,0)", "rgb(0,0,0)", "rgb(0,0,0)",
          "rgb(0,0,0)", "rgb(0,0,0)", "rgb(255,255,255)",
        ],
        colorMark: [
          0, 2, 3, 4,
          6, 9, 14
        ],
        titleText: 'm',
      },
      rwave: {
        color: [
          'rgb(0, 0, 232)', 'rgb(0, 71, 255)', 'rgb(0, 162, 255)', "rgb(0, 255, 255)",
          "rgb(91, 255, 163)", 'rgb(0, 255, 0)', 'rgb(255, 255, 0)',
          'rgb(255, 143, 0)', 'rgb(210, 0, 0)', 'rgb(132, 21, 22)'
        ],
        textcolor: ['rgb(255,255,255)', 'rgb(255,255,255)', 'rgb(255,255,255)',
          'rgb(0,0,0)', 'rgb(0,0,0)', 'rgb(0,0,0)',
          'rgb(0,0,0)', 'rgb(0,0,0)', 'rgb(255,255,255)', 'rgb(255,255,255)'],
        colorMark: [
          0, 0.5, 1, 1.5,
          2, 3, 4,
          5, 7, 10
        ],
        titleText: 'm',
      },
      tide: {
        color: [
          'rgb(0, 0, 232)', 'rgb(0, 71, 255)', 'rgb(0, 162, 255)',
          'rgb(0, 255, 255)', 'rgb(91, 255, 163)', 'rgb(185, 255, 69)',
          'rgb(255, 143, 0)', 'rgb(210, 0, 0)', 'rgb(132, 21, 22)'
        ],
        textcolor: [
          "rgb(255,255,255)", "rgb(255,255,255)", "rgb(0,0,0)",
          "rgb(0,0,0)", "rgb(0,0,0)", "rgb(0,0,0)",
          "rgb(0,0,0)", "rgb(0,0,0)", "rgb(0,0,0)"
        ],
        colorMark: [0, 50, 100, 150, 200, 250, 300, 350, 400],
        titleText: 'cm',
      },
      surge: {
        color: [
          'rgb(0,0,143)', 'rgb(0, 48, 255)', 'rgb(0, 223, 255)',
          'rgb(143, 255, 112)', 'rgb(255, 207, 0)', 'rgb(255, 32, 0)', 'rgb(128, 0, 0)'],
        textcolor: [
          "rgb(255,255,255)", "rgb(255,255,255)", "rgb(0,0,0)", "rgb(0,0,0)",
          "rgb(0,0,0)", "rgb(255,255,255)", "rgb(255,255,255)"
        ],
        colorMark: [-50, 0, 50, 100, 150, 200, 250],
        // colorMark: [-5, 0, 5, 10, 15, 20, 25],
        titleText: 'cm',
        // titleText: 'm',
        // { "color": "rgb(0, 31, 255)", "value": 0 },
        // { "color": "rgb(71, 94, 255)", "value": 5 },
        // { "color": "rgb(54, 152, 237)", "value": 10 },
        // { "color": "rgb(253, 255, 0)", "value": 15 },
        // { "color": "rgb(208, 88, 44)", "value": 20 },
        // { "color": "rgb(250, 11, 10)", "value": 25 },
        // { "color": "rgb(187, 13, 19)", "value": 30 }
      },
    };
    // 新加的动态改bar颜色
    Config.scalarColor[type].forEach(item => {
      dataObj[type].colorMark.push(item.value)
    })
    let colorbar = dataObj[type].color;
    let colorMark = dataObj[type].colorMark;
    let textcolor = dataObj[type].textcolor;
    colorbar.reverse();
    colorMark.reverse();
    textcolor.reverse();

    let widthStr = '36px';
    let heightStr = '28px';
    let fontSizeStr = '14px';
    var can = document.getElementById("scalarLegend");
    if (!can) return
    while (can.firstChild) can.removeChild(can.firstChild)
    let fone = document.createElement('div');
    fone.style.backgroundColor = "rgba(255,255,255,1)";
    fone.innerText = dataObj[type].titleText;
    fone.style.height = heightStr;
    fone.style.width = widthStr;
    fone.style.textAlign = 'center';
    fone.style.lineHeight = heightStr;
    fone.style.fontSize = fontSizeStr;
    can.appendChild(fone);
    let domH = document.body?.clientHeight ?? 1080,
      domScale = domH > 1080 ? 1 : domH / 1080
    can.style.transform = `scale(${domScale})`
    for (let i = 0; i < colorbar.length; i++) {
      let fone = document.createElement('div');
      fone.style.backgroundColor = colorbar[i];
      fone.innerText = colorMark[i];
      fone.style.height = heightStr;
      fone.style.width = widthStr;
      fone.style.textAlign = 'center';
      fone.style.lineHeight = heightStr;
      fone.style.fontSize = fontSizeStr;
      fone.style.color = textcolor[i];
      can.appendChild(fone);
    }
  },
});

export default function (options) {
  return new L.Scalarlayer(options);
};